package com.rongmai.web.bo.feign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongmai.db.dto.CompanyDTO;
import com.rongmai.db.dto.tyc.TycResponse;
import com.rongmai.db.model.Label;
import com.rongmai.db.vo.CompanyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

@Slf4j
@Service
public class CompanyFeignBo {

    @Value("${TYC_REMOTE_URL:}")
    private String tycRemoteUrl;
    @Value("${TYC_REMOTE_TOKEN:}")
    private String tycRemoteToken;


    public List<CompanyVo> vagueQuery(CompanyVo companyVo) {
        String name = companyVo.getName();
        List<CompanyVo> result = executeGet(name);
        log.info("调用天眼查接口返回结果:{}", JSON.toJSONString(result));
        return result;
    }

    protected List<CompanyVo> executeGet(String name) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result;
        try {
            String url = tycRemoteUrl + name;
            HttpGet get = new HttpGet(url);
            // 设置header
            get.setHeader("Authorization", tycRemoteToken);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            JSONObject jsonObject = JSON.parseObject(result);
            Integer errorCode = jsonObject.getInteger("error_code");
            if (errorCode==0) {
                String com = jsonObject.getString("result");
                TycResponse tycResponse = JSON.parseObject(com, TycResponse.class);
                return tycResponse.getItems();
            }
        } catch (Exception e) {
            log.error("调用天眼查接口异常", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return Collections.emptyList();
    }
}
